//
//  SEOrderExamineViewController.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/16.
//

import UIKit

enum SEOrderExamineViewControllerFromType {
    case profile
    case payexamine
}

class SEOrderExamineViewController: SEBaseViewController {
    
    // MARK: - getter
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.se_header = SERefreshHeader { [weak self] in self?.loadNewData() }
            tableView.se_footer = SERefreshFooter { [weak self] in self?.loadMoreData() }
            tableView.se_empty = SEEmptyView { [weak self] in self?.requestMyExamineList() }
            tableView.estimatedRowHeight = 184
            tableView.rowHeight = UITableView.automaticDimension
            tableView.register(SEOrderExamineCell.nibForCell(),
                               forCellReuseIdentifier: SEOrderExamineCell.reuseIdentifier())
        }
    }

    var viewModel = SEExamineListViewModel()

    init(with fromType: SEOrderExamineViewControllerFromType) {
        viewModel.fromType = fromType
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        requestMyExamineList()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.disablePopGesture = viewModel.fromType == .payexamine
    }

    override func popBack() {
        navigationController?.popToRootViewController(animated: true)
    }

    override func setupUI() {
        super.setupUI()
        viewModel.updateData = { [weak self] status in
            self?.tableView.se_empty?.allowShow = true
            self?.endRefreshing()
            switch status {
            case .success:
                self?.tableView.reloadData()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestMyExamineList)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.cancelHandler = {status in
            switch status {
            case .success:
                SEHUD.show(message: "取消成功")
                self.requestMyExamineList()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestMyExamineList)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

}

// MARK: - UITableViewDataSource

extension SEOrderExamineViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEOrderExamineCell.reuseIdentifier()) as! SEOrderExamineCell
        cell.delegate = self
        cell.update(with: viewModel.rowViewModel(indexPath: indexPath))
        return cell
    }
}

// MARK: - UITableViewDelegate

extension SEOrderExamineViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
    }
}

// MARK: - SEOrderExamineCellDelegate

extension SEOrderExamineViewController: SEOrderExamineCellDelegate {
    // TODO:
    func orderExamineCell(_ cell: SEOrderExamineCell, didClickedDetailWith viewModel: SEExamineDetailViewModel) {
        self.viewModel.selectedViewModel = viewModel
        pushToOrderExamineDetailVC()
    }

    func orderExamineCell(_ cell: SEOrderExamineCell, didClickedPayWith viewModel: SEExamineDetailViewModel) {
        self.viewModel.selectedViewModel = viewModel
        pushToExamineOrderVC()
    }

    func orderExamineCell(_ cell: SEOrderExamineCell, didClickedCancelWith viewModel: SEExamineDetailViewModel) {
        self.viewModel.selectedViewModel = viewModel
        requestCancelCheck()
    }
}

// MARK: - push event

private extension SEOrderExamineViewController {
    /// 跳转 订单 详情
    func pushToOrderExamineDetailVC() {
        let detailVc = SEOrderExamineDetailViewController(with: viewModel.selectedViewModel.model.id)
        detailVc.title = "检查订单详情"
        detailVc.cancelCheckItemSuccess = {
            self.requestMyExamineList()
        }
        navigationController?.pushViewController(detailVc, animated: true)
    }

    /// 跳转 订单 支付
    func pushToExamineOrderVC() {
        let vc = SEExamineOrderViewController(with: viewModel.selectedViewModel.model.id, fromType: .examineOrderList)
        vc.paySuccessHandler = {
            self.requestMyExamineList()
        }
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - APIRequest
extension SEOrderExamineViewController {
    @objc private func requestMyExamineList() {
        tableView.se_header?.beginRefreshing()
    }

    private func endRefreshing() {
        tableView.se_footer_hidden = false
        tableView.endHeaderRefreshing()
        tableView.endFooterRefreshing(hasMore: viewModel.hasMore)
    }

    private func loadNewData() {
        viewModel.page = 1
        viewModel.requestMyExamineList(selectSource: 4)
    }

    private func loadMoreData() {
        viewModel.page += 1
        viewModel.requestMyExamineList(selectSource: 4)
    }

    @objc private func requestCancelCheck() {
        viewModel.requestCancelCheck()
    }
}

